﻿using System.Collections;
using System.Collections.Generic;
using UnityEditor;
using UnityEngine;

public class FindMisCs : EditorWindow
{
    [MenuItem("Tools/Find Missing Scripts")]
    static void FindMissingScriptsMenu()
    {
        List<GameObject> results = new List<GameObject>();

        // 遍历所有预制体和场景对象
        foreach (var guid in AssetDatabase.FindAssets("t:Prefab"))
        {
            string path = AssetDatabase.GUIDToAssetPath(guid);
            GameObject prefab = AssetDatabase.LoadAssetAtPath<GameObject>(path);
            CheckForMissingScripts(prefab, results);
        }

        // 当前场景中的对象
        foreach (GameObject go in Resources.FindObjectsOfTypeAll<GameObject>())
        {
            CheckForMissingScripts(go, results);
        }

        // 输出结果
        if (results.Count == 0)
        {
            Debug.Log("No missing scripts found!");
            return;
        }

        Debug.LogWarning($"Found {results.Count} objects with missing scripts:");
        foreach (var go in results)
        {
            Debug.LogWarning($"Missing script in: {GetFullPath(go)}", go);
        }
    }

    static void CheckForMissingScripts(GameObject go, List<GameObject> results)
    {
        Component[] components = go.GetComponents<Component>();
        foreach (Component component in components)
        {
            if (component == null)
            {
                results.Add(go);
                break;
            }
        }
        for (int i = 0; i < go.transform.childCount; i++)
        {
            CheckForMissingScripts(go.transform.GetChild(i).gameObject, results);
        }

    }

    static string GetFullPath(GameObject go)
    {
        string path = go.name;
        Transform parent = go.transform.parent;
        while (parent != null)
        {
            path = parent.name + "/" + path;
            parent = parent.parent;
        }
        return path;
    }
}
